package com.xiaoxin.lease.web.admin.service.impl;

import com.xiaoxin.lease.common.minio.MinioConfiguration;
import com.xiaoxin.lease.common.minio.MinioProperties;
import com.xiaoxin.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioProperties properties;

    @Autowired
    private MinioClient client;


    @Override
    public String upload(MultipartFile file) throws Exception {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //创建新的文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        originalFilename = sdf.format(new Date())+"/"+ UUID.randomUUID().toString().replaceAll("-","")+"_"+originalFilename;
        client.putObject(PutObjectArgs.builder().stream(file.getInputStream(),file.getSize(),-1)
                .contentType(file.getContentType())
                .bucket(properties.getBucketName())
                .object(originalFilename)
                .build());

        return String.format("%s/%s", properties.getEndpoint(),properties.getBucketName()+"/"+ originalFilename);
    }
}
